package com.example.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.HttpClientUtil;
import com.example.common.Result;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;

    public Result loginWithWeChat(String code) {
        String openId = getOpenId(code);
        User user = userMapper.getUserByUserId(openId);
        if (user == null) {
            User one = new User();
            one.setUserId(openId);
            userMapper.addUser(one);
            return Result.success(one);
        }else {
            return Result.success(user);
        }
    }

    private String getOpenId(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", "wx97cc76e30786d763");
        params.put("secret", "49b0f98f48740aa5fe496e476ae999e6");
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String response = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSON.parseObject(response);
        return jsonObject.getString("openid");
    }

    public Result updateUser(User user) {
        if(!userMapper.updateUser(user)){
            return Result.error("更新失败");
        }
        User result = userMapper.getUserByUserId(user.getUserId());
        return Result.success(result);
    }

    public Result getUser(User user) {
        User result = userMapper.getUserByUserId(user.getUserId());
        return Result.success(result);
    }
}
